package product;

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JLabel;
import javax.swing.SwingConstants;

import product.ChulList.myColorRenderer;

import java.awt.Font;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.ImageIcon;

public class MemberMonth2 extends JInternalFrame {
			
			String year = "";  //콤보박스 초기값
			String month = "01";   //콤보박스 초기값
			
			SemiChul sc;
			ProductMain3 pm;

	DefaultTableModel model;
	TableColumn column = null;

	private JScrollPane scrollPane;
	private JTable table;
	private JButton btnNewButton;
	JComboBox yearcombo;
	JComboBox monthcombo;
	private JLabel sss;

	public MemberMonth2(SemiChul sc, ProductMain3 pm) {
		super("월별현황", false, true, false, true);
		addInternalFrameListener(new InternalFrameAdapter() {
			@Override
			public void internalFrameClosing(InternalFrameEvent e) {
				closing();
			}
		});
		this.sc = sc;
		this.pm = pm;
		Vector<String> colNames = new Vector<String>(); // 벡터에 테이블항목을 저장하기위해서
		colNames.add("");
		colNames.add("");
		colNames.add("");
		colNames.add("");
		colNames.add("");
		colNames.add("");
		colNames.add("");
		model = new DefaultTableModel(colNames, 0){
			public boolean isCellEditable(int rowIndex, int mColIndex) {
				return false;
			}
		};
		setBounds(100, 100, 314, 286);
		getContentPane().setLayout(null);
		getContentPane().add(getBtnNewButton());
		getContentPane().add(getYearcombo());
		getContentPane().add(getMonthcombo());
		getContentPane().add(getSss());
		getContentPane().add(getScrollPane());

		for (int i = 0; i < 7; i++) {
			column = table.getColumnModel().getColumn(i);
			column.setPreferredWidth(36); // sport column is bigger
		}
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(12, 37, 274, 210);
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}

	private JTable getTable() {
		if (table == null) {
			table = new JTable(model);
			table.setFont(new Font("굴림", Font.BOLD, 15));
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		}
		return table;
	}

	private JComboBox getYearcombo() {
		if (yearcombo == null) {
			yearcombo = new JComboBox();
			yearcombo.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					if(e.getStateChange() == ItemEvent.SELECTED){
						year =(String)(e.getItem());
					}
				}
			});
			yearcombo.setBounds(12, 10, 71, 21);
			try {
				String sql = "select distinct to_char(chuldate, 'YYYY') from chuldata";
				PreparedStatement pstmt = pm.conn.prepareStatement(sql);
				ResultSet rs = pstmt.executeQuery();
				ResultSetMetaData rsm = rs.getMetaData();
				while(rs.next()){
					for(int i = 1; i <= rsm.getColumnCount(); i++){
						yearcombo.addItem(rs.getString(i) + "");    //콤보 박스 년 칸에 데이터에 있는 년만 가져와서 저장
						year = rs.getString(1) + "";  //가져온 값중 첫 값을 초기값으로 지정하기 위해 넣어줌
					}
				}
				rs.close();
				pstmt.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}	
		}
		return yearcombo;
	}

	private JComboBox getMonthcombo() {
		if (monthcombo == null) {
			monthcombo = new JComboBox();
			monthcombo.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent ev) {
					if(ev.getStateChange() == ItemEvent.SELECTED){
						month = (String)(ev.getItem());
					}
				}
			});
			monthcombo.setBounds(95, 10, 58, 21);
			// 콤보박스 월 칸에 01 ~ 12월 저장
			for(int m = 1; m < 10; m++) {
				monthcombo.addItem("0" + m);
			}
			for(int m = 10; m < 13; m++){
				monthcombo.addItem("" + m);
			}
		}
		return monthcombo;
	}
	
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("조회");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					mm2chul();
				}
			});
			btnNewButton.setBounds(165, 10, 81, 21);
		}
		return btnNewButton;
	}
	
	public void mm2chul(){
		try {
			for(int i = table.getRowCount()-1; i >= 0; i--){
				model.removeRow(i);
			}	
			String name = pm.logincode;  // 로그인 할때 입력한 아이디
			String sql = "select to_char(chuldate, 'DD'), chultype from chuldata where memberid = '" + name + "' and to_char(chuldate, 'YYYY') = '" + year + "' and to_char(chuldate, 'MM') = '" + month + "'";
			PreparedStatement pstmt = pm.conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			ResultSetMetaData rsm = rs.getMetaData();
			Vector r = new Vector<>();
			Vector d = new Vector<>();
			int rcnt = 1;
			int dcnt = 1;
			boolean flag = false;
			sss.setVisible(true);
			while(rs.next()){
				sss.setVisible(false);
				flag = true;
				for(int i = 1; i <= rsm.getColumnCount(); i++){
					if(i == 1){
						r.add(rs.getString(i));
						rcnt++;
					}
					if(i == 2){ // 출 타입 찍을떄
						if(rs.getString(i).equals("0")){
							d.add("결근");
						}
						else if(rs.getString(i).equals("1")){
							String day = month + "-" +  r.lastElement() + "";
							String sql2 = "select distinct h.holytype from holydata h, chuldata c where h.memberid = c.memberid and c.memberid = '" + name + "' and chultype = 1 and to_char(holydate, 'MM-DD') = '" + day + "'";
							PreparedStatement pstmt2 = pm.conn.prepareStatement(sql2);
							ResultSet rs2 = pstmt2.executeQuery();
							ResultSetMetaData rsm2 = rs.getMetaData();
							while(rs2.next()){
								for(int k = 1; k < rsm2.getColumnCount(); k ++){ // 휴가가 있을 경우 휴가를 출력
									if(rs2.getString(k).equals("0")){
										d.add("내규");
									}
									else if(rs2.getString(k).equals("1")){
										d.add("월차");
									}
									else if(rs2.getString(k).equals("2")){
										d.add("연차");
									}
									else if(rs2.getString(k).equals("3")){
										d.add("생리");
									}
									else{
										d.add("기타");
									}
								}
							}
							if(rs2.next() == false){
								d.add("출근");		//휴가가 없을시 출근을 넣음		
							}
							rs2.close();
							pstmt2.close();
						}
						dcnt++;
					}
				}
				if(rcnt == 8){								
					model.addRow(r);
					rcnt = 1;
					r = new Vector<>();
				}
				if(dcnt == 8){
					model.addRow(d);
					dcnt = 1;
					d = new Vector<>();
				}
			}
			if(flag){
				for(int i = 0; i < 7; i++){
					r.add("");
					d.add("");
				}
				model.addRow(r);
				model.addRow(d);
			}
			table.setModel(model);
			tbc();
//			tbcenter();
			rs.close();
			pstmt.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}	
	}
	
	public void tbc(){ //테이블 색 변경 메소드
		table.setDefaultRenderer(Object.class, new myColorRenderer());
	}
	
	public void tbcenter(){ //테이블 가운데 정렬 메소드
		DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
		dtcr.setHorizontalAlignment(SwingConstants.CENTER);
		TableColumnModel tcm = table.getColumnModel();
		for(int i = 0; i < tcm.getColumnCount(); i++){
			tcm.getColumn(i).setCellRenderer(dtcr);
		}
	}
	
	public class myColorRenderer extends DefaultTableCellRenderer { 

		 public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,
		                                                boolean hasFocus, int row, int column) 
		 { 
		 
		  Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 
		  
		  String s = table.getModel().getValueAt(row, column).toString(); 
		  
		  //if구문의 내용은 테이블에 따라 다르니 적절한 코딩하여야 한다.
		  //참고로 rowIndex, colIndex는 0부터 시작한다.
		  if(s.equalsIgnoreCase("결근")){ 
		   comp.setBackground(Color.RED); 
		   comp.setForeground(Color.YELLOW);
		  }
		  else if(s.equalsIgnoreCase("출근")){ 
		   comp.setBackground(Color.CYAN); 
		   comp.setForeground(Color.BLACK); 
		  }
		  else if(row % 2 == 0){
			  comp.setBackground(Color.PINK);
			  comp.setForeground(Color.black);
		  }
		  else{
			  comp.setBackground(Color.WHITE); 
			  comp.setForeground(Color.black);  
		  }
		  if(s.equalsIgnoreCase("")){
			  comp.setBackground(Color.WHITE); 
			  comp.setForeground(Color.black); 
		  }
		  
		  return( comp ); 
		 } 
		}
	
	public void closing(){
		pm.closeMemberMonth2();
		pm.mm2 = null;
	}
	private JLabel getSss() {
		if (sss == null) {
			sss = new JLabel("");
			sss.setIcon(new ImageIcon("C:\\Users\\jhta\\Downloads\\이미지\\아이콘\\번개.gif"));
			sss.setBounds(-90, -10, 500, 280);
		}
		return sss;
	}
}
